<?php
	/*
	 * File: login.php
	 * Last modification: 20.07.2011
	 * Author(s): kivio.wanderley
	 * 
	 */
?>
	
<?php /** UPPER PHP CODE */

	# Get APIs and INCs
	$t_core_dir = dirname( __FILE__ ).DIRECTORY_SEPARATOR.'core'.DIRECTORY_SEPARATOR;
	require_once($t_core_dir . 'core_api.php');
	
	# Start session
	if( ! isset($_SESSION) ) session_start();
?>

<?php /** MIDDLE PHP CODE */
	# Verify any user was already logged in
	if(isset($_SESSION['USER']) && 
	   isset($_SESSION['ACCESS']) && 
	   isset($_SESSION['CREATED']) && 
	   isset($_SESSION['LAST_ACTIVITY']) ) 
	{
		print_header_redirect( 'main_page.php?page=home_page' );
	}
	
	# Try to make the connection
	if( !datab_is_connected() ) {
		config_get_global_array();
		if(!datab_connect( config_get('host'), (int)config_get('port'), config_get('database'), 
					   config_get('user'), config_get('password') ))
		{
			print_header_redirect( 'login_page.php?erro=1004' ); //Erro ao conectar-se ao banco de dados
		}
		config_unset();

		$t_user = gpc_get_string('log_user');
		$t_pass = gpc_get_string('log_pass');

		# If empty return with error
		if( $t_user == null || $t_user == "" || $t_pass == null || $t_pass == "" ) { 
			print_header_redirect( 'login_page.php?erro=1001' );
		}

		# Prepare strings for validation
		$t_user = datab_prepare_string('log_user', $t_user);
		$t_pass = auth_anti_injection($t_pass);
		$t_pass = md5($t_pass);
		$t_pass = trim($t_pass);
		$t_pass = "'".$t_pass."'";

		# Get user ID by name
		$t_user_id = auth_get_user_id_by_name($t_user);

		# If no user return with error
		if( $t_user_id == null || $t_user_id == "" ) { 
			print_header_redirect( 'login_page.php?erro=1002' );
		}

		$t_user_row = auth_get_user_row($t_user_id);
				
		# Check user login information
		if( auth_user_pass($t_user_id, $t_pass) ) {
			
			$_SESSION['USER'] = $t_user; //Save on Session
			$_SESSION['ACCESS'] = $t_user_row['access'];
	
			# Enable user if it was disabled
			if( ! datab_user_get_status($t_user_id)) datab_user_change_status($t_user_id, true);

			print_header_redirect( 'main_page.php?page=home_page' );
		} else {
			print_header_redirect( 'login_page.php?erro=1002' );
		}
		
	}
?>